package com.xcexample.adclasscard.main

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.google.gson.GsonBuilder
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.tencent.mmkv.MMKV
import com.xcexample.adclasscard.GlideHelper
import com.xcexample.adclasscard.databinding.ActivityMainBinding
import com.xcexample.adclasscard.log.LogUtils
import com.xcexample.adclasscard.login.AppUpdateData
import com.xcexample.adclasscard.login.LoginFragment
import com.xcexample.adclasscard.login.LoginResponse
import com.xcexample.adclasscard.login.LoginResponseData
import com.xcexample.adclasscard.login.LogoutFragment
import com.xcexample.adclasscard.login.UpdateResponse
import com.xcexample.adclasscard.net.ApiFactory
import com.xcexample.adclasscard.net.BaseURL
import com.xcexample.adclasscard.view.UpdateVersionDialog
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import com.youth.banner.indicator.RoundLinesIndicator
import com.ys.rkapi.MyManager
import okhttp3.ResponseBody
import org.json.JSONException
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.util.Calendar


class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    val updateVersionDialog by lazy {
        UpdateVersionDialog(this@MainActivity)
    }
    var localName = ""
    var currentIndex = 0
    var data: ArrayList<String> = arrayListOf()

    private val handler2: Handler = Handler()
    private val loopRunnable2: Runnable = object : Runnable {
        override fun run() {
            getHomeData()
            handler2.postDelayed(this, 300000)
        }
    }

    fun write_sys_fs(sys_fs: String?, value: Int) {
        var mode = "1"
        try {
            if (value == 0) mode = "0"
            val fops = FileOutputStream(sys_fs)
            fops.write(mode.toByteArray())
            fops.flush()
            fops.close()
        } catch (e: FileNotFoundException) {
            Log.d("err", "found error")
        } catch (e: IOException) {
            Log.d("err", "IO error")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        sendBroadcast(Intent("android.intent.action.hidebar"))
        val decorView = window.decorView
        val uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN
        decorView.systemUiVisibility = uiOptions
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

//        write_sys_fs("/proc/wdt", 0)

        val packageManager = packageManager
        val packageInfo = packageManager.getPackageInfo(packageName, 0)
        localName = packageInfo.versionName

        if (MMKV.defaultMMKV().decodeString("token").isNullOrEmpty()) {
            LoginFragment {
                if (it.isNullOrEmpty()) {
                    startActivity(Intent(this, MainActivity::class.java))
                    finish()
                    return@LoginFragment
                }
                getHomeData()
            }.show(supportFragmentManager, "")
        } else {
            getHomeData()

        }
        binding.logout.setOnLongClickListener {
            var token = MMKV.defaultMMKV().decodeString("token")
            if (!token.isNullOrEmpty()) {
                LogoutFragment {}.show(supportFragmentManager, "")
            }
            true
        }

        if (!hasPermissions(this, PERMISSIONS_ALL)) {
            ActivityCompat.requestPermissions(this, PERMISSIONS_ALL, all)
        }

        handler2.post(loopRunnable2)
    }

    private val all = 2
    private val PERMISSIONS_ALL = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.REQUEST_INSTALL_PACKAGES,
    )

    override fun onDestroy() {
        sendBroadcast(Intent("android.intent.action.showbar"))
        handler2.removeCallbacks(loopRunnable2)
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
    }

    var retry = 0
    private fun getHomeData() {
        if (MMKV.defaultMMKV().decodeString("token").isNullOrEmpty()) return
        retry++
        var retrofit = ApiFactory.create(BaseURL, true)
        var call = retrofit.getHome()
        call.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>, response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                LogUtils.e("result:$json")
                if (json.isNullOrEmpty()) return
                try {
                    val gson = GsonBuilder().create()
                    val obj = gson.fromJson(json, ADBean::class.java)
                    LogUtils.e("result:$obj")
                    if (obj.code == 0) {
                        var result = obj.data

                        if (result.resource?.isEmpty() == true || result.resource == null) {
                            binding.bannerEmpty.visibility = View.VISIBLE
                        } else {
                            binding.bannerEmpty.visibility = View.GONE
                        }
                        data = result.resource ?: ArrayList()
                        if (result.type == "img") {
                            binding.mainBanner.visibility = View.VISIBLE
                            binding.mainBanner.setAdapter(ImageAdapter(data))
                            binding.mainBanner.isAutoLoop(true)
                            binding.mainBanner.setLoopTime(5000)
                            binding.mainBanner.setIndicatorSelectedColor(Color.WHITE)
                            binding.mainBanner.indicator = RoundLinesIndicator(this@MainActivity)
                            binding.mainBanner.start()
                        } else {
                            binding.video.visibility = View.VISIBLE
                            binding.video.setUp(
                                data[currentIndex],
                                true,
                                cacheDir,
                                null,
                                ""
                            )
                            binding.video.getTitleTextView().setVisibility(View.GONE)
                            binding.video.getBackButton().setVisibility(View.GONE)
                            binding.video.getFullscreenButton().setVisibility(View.GONE)
                            binding.video.getStartButton().setVisibility(View.GONE)
                            binding.video.setReleaseWhenLossAudio(true)
                            binding.video.setAutoFullWithSize(false)
                            binding.video.setDismissControlTime(0)
                            binding.video.setClickable(false)
                            binding.video.setEnabled(false)
                            binding.video.setLongClickable(false)
//                            binding.video.setPlayPosition(position)
                            binding.video.startPlayLogic()

                            //禁止滑动
                            binding.video.setIsTouchWiget(false)
                            binding.video.setVideoAllCallBack(object : GSYSampleCallBack() {
                                override fun onPlayError(url: String, vararg objects: Any) {
                                    super.onPlayError(url, *objects)
                                }

                                override fun onClickStop(url: String, vararg objects: Any) {
                                    super.onClickStop(url, *objects)

                                }

                                override fun onPrepared(url: String, vararg objects: Any) {
                                    super.onPrepared(url, *objects)
                                }

                                override fun onStartPrepared(url: String, vararg objects: Any) {
                                    super.onStartPrepared(url, *objects)
                                }

                                override fun onAutoComplete(url: String, vararg objects: Any) {
                                    if (currentIndex + 1 < data.size) {
                                        currentIndex += 1
                                    } else {
                                        currentIndex = 0
                                    }
                                    binding.video.setUp(
                                        data[currentIndex],
                                        true,
                                        cacheDir,
                                        null,
                                        ""
                                    )
                                    binding.video.startPlayLogic()
                                }
                            })

                        }

                    } else {
                        if (obj.code == 401) {
                            autoLogin()
                        }
                        Toast.makeText(this@MainActivity, obj.msg, Toast.LENGTH_SHORT).show()
                    }

                } catch (e: JSONException) {
                    e.printStackTrace()
                }

            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {
                if (retry < 10) {
                    retry++
                    getHomeData()
                } else retry = 0
            }
        })

        updateOnline()
        autoConfig()
    }

    private fun autoLogin() {
        val defaultMMKV = MMKV.defaultMMKV()
        defaultMMKV.encode("token", "")
        var account = defaultMMKV.decodeString("account", "")
        var pass = defaultMMKV.decodeString("pass", "")
        var retrofit = ApiFactory.create(BaseURL, false)
        var call = retrofit.loginByPwd(account, pass, "")
        call!!.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>, response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                try {
                    val gson = GsonBuilder().create()
                    val obj = gson.fromJson(json, LoginResponse::class.java)
                    LogUtils.e("result:$obj")
                    if (obj.code == 0) {
                        var fromJson = gson.fromJson(
                            obj?.data.toString(), LoginResponseData::class.java
                        )
                        val defaultMMKV = MMKV.defaultMMKV()
                        defaultMMKV.encode("token", fromJson?.access_token)
                        defaultMMKV.encode("account", account)
                        defaultMMKV.encode("pass", pass)
                        getHomeData()

                    } else {
                        Toast.makeText(
                            this@MainActivity, obj.msg, Toast.LENGTH_SHORT
                        ).show()
                    }

                } catch (e: JSONException) {
                    e.printStackTrace()
                }

            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {

            }
        })
    }

    private fun autoConfig() {
        var retrofit = ApiFactory.create(BaseURL, true)
        var call = retrofit.autoConfig()
        call.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>,
                response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                if (!json.isNullOrEmpty()) {
                    try {
                        val gson = GsonBuilder().create()
                        val obj = gson.fromJson(json, AutoCloseBean::class.java)
                        LogUtils.e("result:$obj")

                        if (obj.code == 0) {
                            var result = obj.data
                            if (result.enable == 1) {

                                /**
                                 * 1、设备开机自启动软件
                                 * 2、班牌软件版本强制升级
                                 * 3、定时开关机/自动开关机。
                                 * 周一是2，周二是3，周三是4，周四是5，周五是6，周六是7，周日是1
                                 */
//                val SUNDAY = 1
//                val MONDAY = 2
//                val TUESDAY = 3
//                val WEDNESDAY = 4
//                val THURSDAY = 5
//                val FRIDAY = 6
//                val SATURDAY = 7

                                //result:[3,2,4,5,6,1]
                                //weekdays周一到周日工作状态,1 为开机，0 为不开机
                                var weekdays = intArrayOf(0, 0, 0, 0, 0, 0, 0)
                                result.week.forEach {
                                    when (it) {
                                        1 -> weekdays[6] = 1
                                        2 -> weekdays[0] = 1
                                        3 -> weekdays[1] = 1
                                        4 -> weekdays[2] = 1
                                        5 -> weekdays[3] = 1
                                        6 -> weekdays[4] = 1
                                        7 -> weekdays[5] = 1
                                    }
                                }
                                val onTime = result.on_time.split(":")
                                val offTime = result.off_time.split(":")

                                var onHour = 0
                                var onMinute = 0

                                var offHour = 0
                                var offMinute = 0
                                onTime.forEachIndexed { index, s ->
                                    when (index) {
                                        0 -> onHour = s.toInt()
                                        1 -> onMinute = s.toInt()
                                    }
                                }
                                offTime.forEachIndexed { index, s ->
                                    when (index) {
                                        0 -> offHour = s.toInt()
                                        1 -> offMinute = s.toInt()
                                    }
                                }

                                val timeon = intArrayOf(
                                    onHour,
                                    onMinute
                                ) //开机时间
                                val timeoff = intArrayOf(
                                    offHour,
                                    offMinute
                                ) //关机时间

//                                weekdays.forEach {
//                                    LogUtils.e("weekdays:"+it.toString())
//                                }
                                var manager = MyManager.getInstance(this@MainActivity)
                                manager.setPowerOnOffWithWeekly(timeon, timeoff, weekdays)

                            }


                        } else {
                            Toast.makeText(this@MainActivity, obj.msg, Toast.LENGTH_SHORT)
                                .show()
                        }

                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }


            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {

            }
        })

    }

    private fun updateOnline() {
        var retrofit = ApiFactory.create(BaseURL, true)
        var call = retrofit.online(MyManager.getInstance(this).ethMacAddress)
        call.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>, response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                if (!json.isNullOrEmpty()) {
                    try {
                        val gson = GsonBuilder().create()
                        val obj = gson.fromJson(json, LoginResponse::class.java)
                        LogUtils.e("result:$obj")
                        if (obj.code == 0) {

                        }
                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }


            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {

            }
        })


    }

    private fun updateApp() {
        var retrofit = ApiFactory.create(BaseURL, true)
        var call = retrofit.appUpdate()
        call.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>, response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                if (!json.isNullOrEmpty()) {
                    try {
                        val gson = GsonBuilder().create()
                        val obj = gson.fromJson(json, UpdateResponse::class.java)
                        LogUtils.e("result:$obj")
                        if (obj.code == 0) {
                            if (obj.data != null) {
                                var version = obj.data?.version
                                var local = localName.split(".")
                                var remote = version?.split(".")
                                Log.e("local: ", "${local}")
                                Log.e("remote: ", "${remote}")
                                remote?.forEachIndexed { index, s ->
                                    if (local.size > index) {
                                        var compareTo = s.toInt().compareTo(local[index].toInt())
                                        Log.e("compareTo: ", "${compareTo}")
                                        if (compareTo > 0) {
                                            obj.data?.let { showUpdateDialog(it) }
                                            return
                                        }
                                    }
                                }
                            }
                        }
                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }


            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {

            }
        })


    }

    private fun showUpdateDialog(updateBean: AppUpdateData) {
        var build = updateVersionDialog.setVersionName("更新版本 V" + updateBean.version)
            .setApk_url(updateBean.apk).setUpdateContent(updateBean.describe)
            .setNotUpdateText("暂不更新").setUpdateText("立即更新")
            .setNotUpdateOnClickListener { view -> }.setUpdateOnClickListener { view ->
            }.build()
        if (build?.isShowing == false) build.show()
    }

    private val receiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (action == Intent.ACTION_DATE_CHANGED) {
//                autoConfig()
            }
        }
    }

    private val PERMISSION_REQUEST_CODE = 1
    private val PERMISSIONS_REQUIRED = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE
    )


    private fun hasPermissions(context: Context, permissions: Array<String>): Boolean {
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(
                    context, permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return false
            }
        }
        return true
    }


    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String?>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 4) {
            updateApp()
        }
    }

    override fun onPause() {
        super.onPause()
        binding.video.onVideoPause()
    }

    override fun onResume() {
        super.onResume()
        binding.video.onVideoResume()
    }


}